#include "modelpreview.h"
#include <QMouseEvent>
#include <QWheelEvent>
#include <QTimerEvent>
#include <QTimer>
#include <QTime>
#include <cmath>
#include <QVector3D>
#include <vector>
#include <QDebug>
#include <QtMath>
#include <limits>

// 新增：处理纹理的包含
#include <QOpenGLTexture>
#include <assimp/material.h>
#include <assimp/texture.h>
#include <QFileInfo>
#include <QDir>

ModelPreview::ModelPreview(QWidget *parent)
    : QOpenGLWidget(parent)
    , m_program(nullptr)
    , m_vertexBuffer(QOpenGLBuffer::VertexBuffer)
    , m_indexBuffer(QOpenGLBuffer::IndexBuffer)
    , m_scene(nullptr)
    , m_modelLoaded(false)
    , m_cameraPosition(0.0f, 0.0f, 5.0f)
    , m_cameraTarget(0.0f, 0.0f, 0.0f)
    , m_cameraUp(0.0f, 1.0f, 0.0f)
    , m_zoom(1.0f)
    , m_rotationSensitivity(0.5f)
    , m_autoAdjustCamera(true)
    , m_animationEnabled(false)
    , m_animationTime(0.0f)
    , m_animationTimer(nullptr)
    , m_currentAnimationIndex(-1)
    , m_isAnimationPlaying(false)
    , m_isAnimationPaused(false)
    , m_currentAnimation(nullptr)
    , m_modelSize(0.0f)
    , m_viewSwitchInProgress(false)
{
    // 设置背景色
    setStyleSheet("background-color: #2c3e50;");
    
    // 初始化动画定时器
    m_animationTimer = new QTimer(this);
    connect(m_animationTimer, &QTimer::timeout, this, [this]() {
        if (m_isAnimationPlaying && !m_isAnimationPaused && m_currentAnimationIndex >= 0) {
            m_animationTime += 0.016f; // 约60FPS
            updateAnimation(m_animationTime);
            adjustCameraForAnimation(); // 在动画播放时调整相机
            update();
        }
    });
}

ModelPreview::~ModelPreview()
{
    if (m_animationTimer) {
        m_animationTimer->stop();
    }
    
    makeCurrent();
    m_vertexBuffer.destroy();
    m_indexBuffer.destroy();
    delete m_program;
    
    // 删除所有纹理对象
    for (GLuint textureID : m_textures) {
        glDeleteTextures(1, &textureID);
    }
    doneCurrent();
}

void ModelPreview::setupUI()
{
    // ModelPreview的UI设置（如果需要的话）
    // 目前这个类主要处理OpenGL渲染，UI设置较少
}

void ModelPreview::setModelScene(const aiScene *scene, const QString &modelPath)
{
    m_scene = scene;
    if (m_scene) {
        loadModelToBuffer(scene, modelPath);
        loadBones(scene);
        loadAnimationList(scene);
        m_modelLoaded = true;
        
        // 计算模型边界框并调整相机
        calculateModelBounds();
        adjustCameraToModel();
        
        qDebug() << "Model loaded with" << m_bones.size() << "bones and" << m_animationList.size() << "animations";
    } else {
        m_modelLoaded = false;
        m_animationEnabled = false;
        m_animationTimer->stop();
    }
    update();
}

void ModelPreview::clearModel()
{
    m_scene = nullptr;
    m_modelLoaded = false;
    m_vertices.clear();
    m_indices.clear();
    m_bones.clear();
    m_boneTransforms.clear();
    m_vertexWeights.clear();
    m_boneNameToIndex.clear();
    
    stopAnimation();
    m_animationList.clear();
    m_currentAnimationIndex = -1;
    m_currentAnimation = nullptr;
    
    update();
}

void ModelPreview::initializeGL()
{
    initializeOpenGLFunctions();
    
    glClearColor(0.2f, 0.2f, 0.2f, 1.0f);
    glEnable(GL_DEPTH_TEST);
    glEnable(GL_CULL_FACE);
    
    // 创建着色器程序
    m_program = new QOpenGLShaderProgram(this);
    m_program->addShaderFromSourceCode(QOpenGLShader::Vertex,
        "#version 120\n"
        "attribute highp vec3 vertexPosition;\n"
        "attribute lowp vec3 vertexColor;\n"
        "attribute highp vec2 vertexTexCoord;\n"
        "attribute highp vec3 vertexNormal;\n"
        "attribute highp vec4 boneIndices;\n"
        "attribute highp vec4 boneWeights;\n"
        "varying lowp vec3 color;\n"
        "varying highp vec2 texCoord;\n"
        "varying highp vec3 normal;\n"
        "varying highp vec3 worldPos;\n"
        "uniform highp mat4 matrix;\n"
        "uniform highp mat4 modelMatrix;\n"
        "uniform highp mat4 boneTransforms[100];\n"
        "void main() {\n"
        "   vec4 totalPosition = vec4(0.0);\n"
        "   vec3 totalNormal = vec3(0.0);\n"
        "   float totalWeight = 0.0;\n"
        "   \n"
        "   // 计算总权重用于归一化\n"
        "   for(int i = 0; i < 4; i++) {\n"
        "       totalWeight += boneWeights[i];\n"
        "   }\n"
        "   \n"
        "   // 应用骨骼变换\n"
        "   if(totalWeight > 0.0) {\n"
        "       for(int i = 0; i < 4; i++) {\n"
        "           if(boneWeights[i] > 0.0) {\n"
        "               float normalizedWeight = boneWeights[i] / totalWeight;\n"
        "               vec4 localPosition = boneTransforms[int(boneIndices[i])] * vec4(vertexPosition, 1.0);\n"
        "               totalPosition += localPosition * normalizedWeight;\n"
        "               \n"
        "               vec3 localNormal = (boneTransforms[int(boneIndices[i])] * vec4(vertexNormal, 0.0)).xyz;\n"
        "               totalNormal += localNormal * normalizedWeight;\n"
        "           }\n"
        "       }\n"
        "   } else {\n"
        "       // 如果没有骨骼权重，使用原始位置\n"
        "       totalPosition = vec4(vertexPosition, 1.0);\n"
        "       totalNormal = vertexNormal;\n"
        "   }\n"
        "   \n"
        "   color = vertexColor;\n"
        "   texCoord = vertexTexCoord;\n"
        "   normal = normalize((modelMatrix * vec4(totalNormal, 0.0)).xyz);\n"
        "   worldPos = (modelMatrix * totalPosition).xyz;\n"
        "   gl_Position = matrix * modelMatrix * totalPosition;\n"
        "}\n"
    );
    
    m_program->addShaderFromSourceCode(QOpenGLShader::Fragment,
        "#version 120\n"
        "varying lowp vec3 color;\n"
        "varying highp vec2 texCoord;\n"
        "varying highp vec3 normal;\n"
        "varying highp vec3 worldPos;\n"
        "uniform sampler2D textureSampler;\n"
        "uniform bool hasTexture;\n"
        "void main() {\n"
        "   vec3 baseColor;\n"
        "   if (hasTexture) {\n"
        "       // 纹理颜色与顶点颜色相乘，实现真实的材质效果\n"
        "       vec3 textureColor = texture2D(textureSampler, texCoord).rgb;\n"
        "       baseColor = textureColor * color;\n"
        "   } else {\n"
        "       // 没有纹理时直接使用顶点颜色\n"
        "       baseColor = color;\n"
        "   }\n"
        "   \n"
        "   // 优化的光照计算 - 确保白色材质显示明亮\n"
        "   vec3 normalizedNormal = normalize(normal);\n"
        "   \n"
        "   // 多方向光照减少阴影\n"
        "   vec3 light1 = normalize(vec3(1.0, 1.0, 1.0));   // 主光源\n"
        "   vec3 light2 = normalize(vec3(-0.5, 0.5, 0.5));  // 补光\n"
        "   vec3 light3 = normalize(vec3(0.0, -1.0, 0.2));  // 底光\n"
        "   \n"
        "   float diff1 = max(dot(normalizedNormal, light1), 0.0);\n"
        "   float diff2 = max(dot(normalizedNormal, light2), 0.0);\n"
        "   float diff3 = max(dot(normalizedNormal, light3), 0.0);\n"
        "   \n"
        "   // 高环境光确保基本可见性\n"
        "   vec3 ambient = 0.6 * baseColor;\n"
        "   \n"
        "   // 多光源漫反射\n"
        "   vec3 diffuse = baseColor * (0.4 * diff1 + 0.2 * diff2 + 0.15 * diff3);\n"
        "   \n"
        "   // 轻微的镜面反射增加立体感\n"
        "   vec3 viewDir = normalize(-worldPos);\n"
        "   vec3 halfDir = normalize(light1 + viewDir);\n"
        "   float spec = pow(max(dot(normalizedNormal, halfDir), 0.0), 32.0);\n"
        "   vec3 specular = 0.1 * spec * vec3(1.0);\n"
        "   \n"
        "   vec3 finalColor = ambient + diffuse + specular;\n"
        "   \n"
        "   // 确保最终亮度\n"
        "   finalColor = clamp(finalColor, 0.0, 1.2);\n"
        "   \n"
        "   gl_FragColor = vec4(finalColor, 1.0);\n"
        "}\n"
    );
    
    m_program->link();
    m_posAttr = m_program->attributeLocation("vertexPosition");
    m_colAttr = m_program->attributeLocation("vertexColor");
    m_texAttr = m_program->attributeLocation("vertexTexCoord");
    m_normalAttr = m_program->attributeLocation("vertexNormal");
    m_boneIndexAttr = m_program->attributeLocation("boneIndices");
    m_boneWeightAttr = m_program->attributeLocation("boneWeights");
    m_matrixUniform = m_program->uniformLocation("matrix");
    m_modelMatrixUniform = m_program->uniformLocation("modelMatrix");
    m_hasTextureUniform = m_program->uniformLocation("hasTexture");
    m_boneTransformsUniform = m_program->uniformLocation("boneTransforms");
}

void ModelPreview::resizeGL(int w, int h)
{
    glViewport(0, 0, w, h);
    m_projection.setToIdentity();
    
    // 使用更合适的近远平面设置
    float aspectRatio = GLfloat(w) / h;
    float nearPlane = 0.001f;
    float farPlane = 1000.0f;
    
    // 如果有模型，根据模型大小调整
    if (m_modelSize > 0) {
        nearPlane = qMax(0.001f, m_modelSize * 0.001f);
        farPlane = qMax(1000.0f, m_modelSize * 100.0f);
    } else {
        // 当模型大小未知时，使用更宽松的范围
        nearPlane = 0.001f;
        farPlane = 10000.0f;  // 更大的远平面
    }
    
    m_projection.perspective(45.0f, aspectRatio, nearPlane, farPlane);
    
    qDebug() << "ResizeGL - Near:" << nearPlane << "Far:" << farPlane << "ModelSize:" << m_modelSize;
}

void ModelPreview::paintGL()
{
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
    
    if (!m_modelLoaded || !m_scene) {
        glClearColor(0.2f, 0.2f, 0.2f, 1.0f);
        glClear(GL_COLOR_BUFFER_BIT);
        return;
    }
    
    m_program->bind();
    
    QMatrix4x4 view;
    view.lookAt(m_cameraPosition, m_cameraTarget, m_cameraUp);
    
    QMatrix4x4 model;
    model.translate(0.0f, 0.0f, 0.0f);
    model.scale(m_zoom);
    model.rotate(m_rotation);
    
    QMatrix4x4 mvp = m_projection * view * model;
    m_program->setUniformValue(m_matrixUniform, mvp);
    m_program->setUniformValue(m_modelMatrixUniform, model);
    
    // 设置骨骼变换uniform
    if (!m_boneTransforms.isEmpty()) {
        int boneCount = qMin(m_boneTransforms.size(), 100);
        m_program->setUniformValueArray(m_boneTransformsUniform, m_boneTransforms.data(), boneCount);
    }
    
    if (!m_vertices.isEmpty()) {
        m_vertexBuffer.bind();
        
        // 设置顶点属性
        m_program->enableAttributeArray(m_posAttr);
        m_program->enableAttributeArray(m_colAttr);
        m_program->enableAttributeArray(m_texAttr);
        m_program->enableAttributeArray(m_normalAttr);
        m_program->enableAttributeArray(m_boneIndexAttr);
        m_program->enableAttributeArray(m_boneWeightAttr);
        
        // 每个顶点19个float：位置(3) + 颜色(3) + 纹理坐标(2) + 法线(3) + 骨骼索引(4) + 骨骼权重(4)
        int stride = 19 * sizeof(float);
        m_program->setAttributeBuffer(m_posAttr, GL_FLOAT, 0, 3, stride);
        m_program->setAttributeBuffer(m_colAttr, GL_FLOAT, 3 * sizeof(float), 3, stride);
        m_program->setAttributeBuffer(m_texAttr, GL_FLOAT, 6 * sizeof(float), 2, stride);
        m_program->setAttributeBuffer(m_normalAttr, GL_FLOAT, 8 * sizeof(float), 3, stride);
        m_program->setAttributeBuffer(m_boneIndexAttr, GL_FLOAT, 11 * sizeof(float), 4, stride);
        m_program->setAttributeBuffer(m_boneWeightAttr, GL_FLOAT, 15 * sizeof(float), 4, stride);
        
        // 调试：输出颜色属性设置信息（仅一次）
        static bool debugShown = false;
        if (!debugShown) {
            qDebug() << "Color attribute location:" << m_colAttr;
            qDebug() << "Position attribute location:" << m_posAttr;
            debugShown = true;
        }
        
        // 设置纹理
        if (!m_textures.isEmpty()) {
            glActiveTexture(GL_TEXTURE0);
            glBindTexture(GL_TEXTURE_2D, m_textures[0]);
            m_program->setUniformValue(m_hasTextureUniform, true);
        } else {
            m_program->setUniformValue(m_hasTextureUniform, false);
        }
        
        // 绘制模型
        if (!m_indices.isEmpty()) {
            m_indexBuffer.bind();
            glDrawElements(GL_TRIANGLES, m_indices.size(), GL_UNSIGNED_INT, 0);
            m_indexBuffer.release();
        } else {
            glDrawArrays(GL_TRIANGLES, 0, m_vertices.size() / 19);
        }
    }
    
    m_program->release();
}

void ModelPreview::mousePressEvent(QMouseEvent *event)
{
    m_lastMousePos = event->pos();
    m_mousePressed = true;
}

void ModelPreview::mouseMoveEvent(QMouseEvent *event)
{
    if (!m_mousePressed) return;
    
    QPoint delta = event->pos() - m_lastMousePos;
    
    // 旋转相机
    QVector3D right = QVector3D::crossProduct(m_cameraPosition - m_cameraTarget, m_cameraUp).normalized();
    QVector3D up = QVector3D::crossProduct(right, m_cameraPosition - m_cameraTarget).normalized();
    
    m_cameraPosition = m_cameraTarget + 
                      QQuaternion::fromAxisAndAngle(up, -delta.x() * m_rotationSensitivity) *
                      QQuaternion::fromAxisAndAngle(right, -delta.y() * m_rotationSensitivity) *
                      (m_cameraPosition - m_cameraTarget);
    
    m_lastMousePos = event->pos();
    update();
}

void ModelPreview::wheelEvent(QWheelEvent *event)
{
    float delta = event->angleDelta().y() / 120.0f;
    m_zoom *= (1.0f + delta * 0.1f);
    m_zoom = qBound(0.01f, m_zoom, 100.0f);
    
    emit scaleChanged(m_zoom);
    update();
}

void ModelPreview::setScale(float scale)
{
    m_zoom = scale;
    update();
    emit scaleChanged(m_zoom);
}

void ModelPreview::resetScale()
{
    // 重置缩放到默认值
    m_zoom = 1.0f;
    
    // 更新视图
    update();
    emit scaleChanged(m_zoom);
    
    qDebug() << "Scale reset to 1.0";
}

void ModelPreview::resetView()
{
    // 重置相机位置
    m_cameraPosition = QVector3D(0.0f, 0.0f, 5.0f);
    m_cameraTarget = QVector3D(0.0f, 0.0f, 0.0f);
    m_cameraUp = QVector3D(0.0f, 1.0f, 0.0f);
    
    // 重置缩放
    m_zoom = 1.0f;
    
    // 重置旋转
    m_rotation = QQuaternion();
    
    // 更新视图
    update();
    emit scaleChanged(m_zoom);
    
    qDebug() << "View reset to default position";
}

void ModelPreview::setAnimationEnabled(bool enabled)
{
    m_animationEnabled = enabled;
    if (!enabled) {
        m_animationTimer->stop();
    }
}

QVector<AnimationInfo> ModelPreview::getAnimationList() const
{
    return m_animationList;
}

void ModelPreview::playAnimation(int animationIndex)
{
    if (animationIndex < 0 || animationIndex >= m_animationList.size()) {
        qWarning() << "Invalid animation index:" << animationIndex;
        return;
    }
    
    stopAnimation();
    
    m_currentAnimationIndex = animationIndex;
    m_currentAnimation = m_scene->mAnimations[animationIndex];
    m_animationDuration = m_animationList[animationIndex].duration;
    m_ticksPerSecond = m_animationList[animationIndex].ticksPerSecond;
    m_animationTime = 0.0f;
    
    m_isAnimationPlaying = true;
    m_isAnimationPaused = false;
    m_animationTimer->start(16); // 60FPS
    
    for (int i = 0; i < m_animationList.size(); i++) {
        m_animationList[i].isPlaying = (i == animationIndex);
    }
    
    qDebug() << "Playing animation:" << m_animationList[animationIndex].name;
    emit animationStateChanged(animationIndex, true);
}

void ModelPreview::stopAnimation()
{
    if (m_animationTimer) {
        m_animationTimer->stop();
    }
    
    m_isAnimationPlaying = false;
    m_isAnimationPaused = false;
    m_animationTime = 0.0f;
    m_currentAnimation = nullptr;
    
    for (int i = 0; i < m_animationList.size(); i++) {
        m_animationList[i].isPlaying = false;
    }
    
    if (m_currentAnimationIndex >= 0) {
        qDebug() << "Stopped animation:" << m_animationList[m_currentAnimationIndex].name;
        emit animationStateChanged(m_currentAnimationIndex, false);
    }
}

void ModelPreview::pauseAnimation()
{
    if (m_isAnimationPlaying && !m_isAnimationPaused) {
        m_animationTimer->stop();
        m_isAnimationPaused = true;
        
        qDebug() << "Paused animation:" << m_animationList[m_currentAnimationIndex].name;
    }
}

void ModelPreview::resumeAnimation()
{
    if (m_isAnimationPlaying && m_isAnimationPaused) {
        m_animationTimer->start(16);
        m_isAnimationPaused = false;
        
        qDebug() << "Resumed animation:" << m_animationList[m_currentAnimationIndex].name;
    }
}

int ModelPreview::getCurrentAnimationIndex() const
{
    return m_currentAnimationIndex;
}

bool ModelPreview::isAnimationPlaying() const
{
    return m_isAnimationPlaying && !m_isAnimationPaused;
}

void ModelPreview::loadModelToBuffer(const aiScene *scene, const QString &modelPath)
{
    m_vertices.clear();
    m_indices.clear();
    
    QFileInfo modelFileInfo(modelPath);
    QString modelDir = modelFileInfo.absolutePath();
    
    // 首先加载骨骼信息
    loadBones(scene);
    
    // 加载纹理
    loadTextures(scene, modelDir);
    
    // 处理所有网格
    // 当将多个网格合并到一个缓冲时，需要跟踪顶点偏移
    unsigned int vertexOffset = 0;
    for (unsigned int i = 0; i < scene->mNumMeshes; i++) {
        const aiMesh *mesh = scene->mMeshes[i];
        
        // 获取该网格的材质信息
        aiColor3D materialDiffuse(0.9f, 0.9f, 0.9f); // 默认明亮颜色
        bool hasTexture = false;
        
        if (mesh->mMaterialIndex < scene->mNumMaterials) {
            const aiMaterial *material = scene->mMaterials[mesh->mMaterialIndex];
            
            // 检查是否有纹理（优先GLTF PBR的BASE_COLOR，其次DIFFUSE，最后UNKNOWN）
            if (material->GetTextureCount((aiTextureType)aiTextureType_BASE_COLOR) > 0 ||
                material->GetTextureCount(aiTextureType_DIFFUSE) > 0 ||
                material->GetTextureCount(aiTextureType_UNKNOWN) > 0) {
                hasTexture = true;
                // 有纹理时使用白色作为基础颜色，让纹理原色显示
                materialDiffuse = aiColor3D(1.0f, 1.0f, 1.0f);
                qDebug() << "Mesh" << i << "has texture (PBR/DIFFUSE/UNKNOWN), using white base color";
            } else {
                // 没有纹理时使用材质颜色
                aiReturn result = material->Get(AI_MATKEY_COLOR_DIFFUSE, materialDiffuse);
                if (result != AI_SUCCESS) {
                    // 如果没有漫反射颜色，尝试获取环境光颜色
                    result = material->Get(AI_MATKEY_COLOR_AMBIENT, materialDiffuse);
                }
                
                // 如果材质颜色太暗，增加亮度
                float maxComponent = qMax(materialDiffuse.r, qMax(materialDiffuse.g, materialDiffuse.b));
                if (maxComponent < 0.3f && maxComponent > 0.0f) {
                    float factor = 0.8f / maxComponent;
                    materialDiffuse.r *= factor;
                    materialDiffuse.g *= factor;
                    materialDiffuse.b *= factor;
                }
                
                qDebug() << "Mesh" << i << "material color:" << materialDiffuse.r << materialDiffuse.g << materialDiffuse.b;
            }
        }
        
        // 处理顶点
        for (unsigned int j = 0; j < mesh->mNumVertices; j++) {
            // 位置
            m_vertices.append(mesh->mVertices[j].x);
            m_vertices.append(mesh->mVertices[j].y);
            m_vertices.append(mesh->mVertices[j].z);
            
            // 颜色 - 优先使用顶点颜色，否则使用材质颜色
            if (mesh->HasVertexColors(0)) {
                m_vertices.append(mesh->mColors[0][j].r);
                m_vertices.append(mesh->mColors[0][j].g);
                m_vertices.append(mesh->mColors[0][j].b);

            } else {
                // 使用材质颜色
                m_vertices.append(materialDiffuse.r);
                m_vertices.append(materialDiffuse.g);
                m_vertices.append(materialDiffuse.b);

            }
            
            // 纹理坐标
            if (mesh->HasTextureCoords(0)) {
                m_vertices.append(mesh->mTextureCoords[0][j].x);
                m_vertices.append(mesh->mTextureCoords[0][j].y);
            } else {
                m_vertices.append(0.0f);
                m_vertices.append(0.0f);
            }
            
            // 法线
            if (mesh->HasNormals()) {
                m_vertices.append(mesh->mNormals[j].x);
                m_vertices.append(mesh->mNormals[j].y);
                m_vertices.append(mesh->mNormals[j].z);
            } else {
                m_vertices.append(0.0f);
                m_vertices.append(1.0f);
                m_vertices.append(0.0f);
            }
            
            // 骨骼索引和权重
            QVector4D boneIndices(0, 0, 0, 0);
            QVector4D boneWeights(0, 0, 0, 0);
            
            // 获取该顶点的骨骼权重
            if (mesh->HasBones()) {
                int weightCount = 0;
                for (unsigned int k = 0; k < mesh->mNumBones; k++) {
                    const aiBone *bone = mesh->mBones[k];
                    for (unsigned int l = 0; l < bone->mNumWeights; l++) {
                        if (bone->mWeights[l].mVertexId == j && weightCount < 4) {
                            boneIndices[weightCount] = m_boneNameToIndex[QString::fromUtf8(bone->mName.C_Str())];
                            boneWeights[weightCount] = bone->mWeights[l].mWeight;
                            weightCount++;
                        }
                    }
                }
            }
            
            // 添加骨骼索引
            m_vertices.append(boneIndices.x());
            m_vertices.append(boneIndices.y());
            m_vertices.append(boneIndices.z());
            m_vertices.append(boneIndices.w());
            
            // 添加骨骼权重
            m_vertices.append(boneWeights.x());
            m_vertices.append(boneWeights.y());
            m_vertices.append(boneWeights.z());
            m_vertices.append(boneWeights.w());
        }
        
        // 处理索引（添加顶点偏移以支持多网格合并）
        for (unsigned int j = 0; j < mesh->mNumFaces; j++) {
            const aiFace &face = mesh->mFaces[j];
            for (unsigned int k = 0; k < face.mNumIndices; k++) {
                m_indices.append(face.mIndices[k] + vertexOffset);
            }
        }

        // 更新偏移到下一个网格的起始位置
        vertexOffset += mesh->mNumVertices;
    }
    
    // 创建顶点缓冲区
    m_vertexBuffer.create();
    m_vertexBuffer.bind();
    m_vertexBuffer.allocate(m_vertices.constData(), m_vertices.size() * sizeof(float));
    
    // 创建索引缓冲区
    if (!m_indices.isEmpty()) {
        m_indexBuffer.create();
        m_indexBuffer.bind();
        m_indexBuffer.allocate(m_indices.constData(), m_indices.size() * sizeof(unsigned int));
    }
    
    qDebug() << "Loaded model with" << m_vertices.size() / 19 << "vertices and" << m_indices.size() << "indices";
    qDebug() << "Loaded" << m_bones.size() << "bones";
    qDebug() << "Total materials in scene:" << scene->mNumMaterials;
    
    // 调试：输出前几个顶点的颜色信息
    if (m_vertices.size() >= 19) {
        qDebug() << "First vertex color:" << m_vertices[3] << m_vertices[4] << m_vertices[5];
    }
}

void ModelPreview::loadBones(const aiScene *scene)
{
    m_bones.clear();
    m_boneNameToIndex.clear();
    m_vertexWeights.clear();
    
    // 加载骨骼信息
    for (unsigned int i = 0; i < scene->mNumMeshes; i++) {
        const aiMesh *mesh = scene->mMeshes[i];
        
        for (unsigned int j = 0; j < mesh->mNumBones; j++) {
            const aiBone *bone = mesh->mBones[j];
            QString boneName = QString::fromUtf8(bone->mName.C_Str());
            
            // 添加骨骼
            if (!m_boneNameToIndex.contains(boneName)) {
                Bone newBone;
                newBone.name = boneName;
                newBone.parentIndex = -1;
                
                // 转换偏移矩阵
                for (int row = 0; row < 4; row++) {
                    for (int col = 0; col < 4; col++) {
                        newBone.offsetMatrix(row, col) = bone->mOffsetMatrix[row][col];
                    }
                }
                
                m_boneNameToIndex[boneName] = m_bones.size();
                m_bones.append(newBone);
            }
            
            // 处理顶点权重
            for (unsigned int k = 0; k < bone->mNumWeights; k++) {
                VertexWeight weight;
                weight.boneIndex = m_boneNameToIndex[boneName];
                weight.weight = bone->mWeights[k].mWeight;
                weight.vertexIndex = bone->mWeights[k].mVertexId;
                m_vertexWeights.append(weight);
            }
        }
    }
    
    // 构建骨骼层次结构
    buildBoneHierarchy(scene->mRootNode, -1);
    
    // 初始化骨骼变换矩阵
    m_boneTransforms.resize(qMax(m_bones.size(), 1)); // 至少保证有一个变换矩阵
    for (int i = 0; i < m_boneTransforms.size(); i++) {
        if (i < m_bones.size()) {
            m_boneTransforms[i].setToIdentity(); // 初始化为单位矩阵
        } else {
            m_boneTransforms[i].setToIdentity();
        }
    }
    
    qDebug() << "Loaded" << m_bones.size() << "bones";
}

void ModelPreview::buildBoneHierarchy(const aiNode *node, int parentIndex)
{
    QString nodeName = QString::fromUtf8(node->mName.C_Str());
    
    if (m_boneNameToIndex.contains(nodeName)) {
        int boneIndex = m_boneNameToIndex[nodeName];
        m_bones[boneIndex].parentIndex = parentIndex;
        
        if (parentIndex >= 0) {
            m_bones[parentIndex].children.append(boneIndex);
        }
        
        parentIndex = boneIndex;
    }
    
    for (unsigned int i = 0; i < node->mNumChildren; i++) {
        buildBoneHierarchy(node->mChildren[i], parentIndex);
    }
}

void ModelPreview::loadAnimationList(const aiScene *scene)
{
    m_animationList.clear();
    m_currentAnimationIndex = -1;
    m_isAnimationPlaying = false;
    m_isAnimationPaused = false;
    
    if (scene->mNumAnimations > 0) {
        qDebug() << "Found" << scene->mNumAnimations << "animations:";
        
        for (unsigned int i = 0; i < scene->mNumAnimations; i++) {
            const aiAnimation *animation = scene->mAnimations[i];
            
            AnimationInfo animInfo;
            animInfo.name = QString::fromUtf8(animation->mName.C_Str());
            animInfo.duration = animation->mDuration;
            animInfo.ticksPerSecond = animation->mTicksPerSecond > 0 ? animation->mTicksPerSecond : 25.0;
            animInfo.channelCount = animation->mNumChannels;
            animInfo.isPlaying = false;
            
            m_animationList.append(animInfo);
            
            qDebug() << "  Animation" << i << ":" << animInfo.name;
            qDebug() << "    Duration:" << animInfo.duration << "Ticks per second:" << animInfo.ticksPerSecond;
            qDebug() << "    Channels:" << animInfo.channelCount;
        }
        
        emit animationListChanged();
    } else {
        qDebug() << "No animations found";
    }
}

void ModelPreview::updateAnimation(double timeInSeconds)
{
    if (m_currentAnimation && m_isAnimationPlaying && !m_isAnimationPaused) {
        updateBoneTransforms(timeInSeconds);
    }
}

void ModelPreview::updateBoneTransforms(double timeInSeconds)
{
    if (!m_currentAnimation || !m_scene) {
        return;
    }
    
    // 计算动画时间
    double timeInTicks = timeInSeconds * m_ticksPerSecond;
    double animationTime = fmod(timeInTicks, m_animationDuration);
    
    // 重置所有骨骼变换为单位矩阵
    for (int i = 0; i < m_bones.size(); i++) {
        m_boneTransforms[i].setToIdentity();
    }
    
    // 计算骨骼变换
    QMatrix4x4 globalInverseTransform;
    
    // 获取根节点的逆变换矩阵
    if (m_scene->mRootNode) {
        for (int row = 0; row < 4; row++) {
            for (int col = 0; col < 4; col++) {
                globalInverseTransform(row, col) = m_scene->mRootNode->mTransformation[row][col];
            }
        }
        globalInverseTransform = globalInverseTransform.inverted();
    }
    
    calculateBoneTransforms(m_scene->mRootNode, globalInverseTransform);
}

void ModelPreview::calculateBoneTransforms(const aiNode *node, const QMatrix4x4 &parentTransform)
{
    QString nodeName = QString::fromUtf8(node->mName.C_Str());
    
    QMatrix4x4 nodeTransform;
    
    // 获取节点的变换矩阵
    for (int row = 0; row < 4; row++) {
        for (int col = 0; col < 4; col++) {
            nodeTransform(row, col) = node->mTransformation[row][col];
        }
    }
    
    // 如果有动画，应用动画变换
    if (m_currentAnimation) {
        // 查找动画通道
        for (unsigned int i = 0; i < m_currentAnimation->mNumChannels; i++) {
            const aiNodeAnim *channel = m_currentAnimation->mChannels[i];
            if (QString::fromUtf8(channel->mNodeName.C_Str()) == nodeName) {
                // 应用动画变换
                double timeInTicks = m_animationTime * m_ticksPerSecond;
                double animationTime = fmod(timeInTicks, m_animationDuration);
                
                // 插值位置
                QVector3D position = interpolatePosition(channel, animationTime);
                // 插值旋转
                QQuaternion rotation = interpolateRotation(channel, animationTime);
                // 插值缩放
                QVector3D scaling = interpolateScaling(channel, animationTime);
                
                // 构建动画变换矩阵
                QMatrix4x4 animTransform;
                animTransform.translate(position);
                animTransform.rotate(rotation);
                animTransform.scale(scaling);
                
                nodeTransform = animTransform;
                break;
            }
        }
    }
    
    QMatrix4x4 globalTransform = parentTransform * nodeTransform;
    
    // 更新骨骼变换
    if (m_boneNameToIndex.contains(nodeName)) {
        int boneIndex = m_boneNameToIndex[nodeName];
        // 正确的骨骼变换公式: FinalTransform = GlobalInverseTransform * GlobalTransform * OffsetMatrix
        m_boneTransforms[boneIndex] = globalTransform * m_bones[boneIndex].offsetMatrix;
    }
    
    // 递归处理子节点
    for (unsigned int i = 0; i < node->mNumChildren; i++) {
        calculateBoneTransforms(node->mChildren[i], globalTransform);
    }
}

void ModelPreview::applyAnimationTransforms()
{
    // 这里可以应用更复杂的动画变换
}

QVector3D ModelPreview::interpolatePosition(const aiNodeAnim* channel, double time)
{
    if (channel->mNumPositionKeys == 0) {
        return QVector3D(0, 0, 0);
    }
    
    // 边界检查
    if (time <= channel->mPositionKeys[0].mTime) {
        const aiVector3D& pos = channel->mPositionKeys[0].mValue;
        return QVector3D(pos.x, pos.y, pos.z);
    }
    
    if (time >= channel->mPositionKeys[channel->mNumPositionKeys - 1].mTime) {
        const aiVector3D& pos = channel->mPositionKeys[channel->mNumPositionKeys - 1].mValue;
        return QVector3D(pos.x, pos.y, pos.z);
    }
    
    // 找到当前时间的关键帧
    for (unsigned int i = 0; i < channel->mNumPositionKeys - 1; i++) {
        if (time < channel->mPositionKeys[i + 1].mTime) {
            // 线性插值
            double factor = (time - channel->mPositionKeys[i].mTime) / 
                           (channel->mPositionKeys[i + 1].mTime - channel->mPositionKeys[i].mTime);
            
            factor = qBound(0.0, factor, 1.0);
            
            const aiVector3D& start = channel->mPositionKeys[i].mValue;
            const aiVector3D& end = channel->mPositionKeys[i + 1].mValue;
            
            return QVector3D(
                start.x + (end.x - start.x) * factor,
                start.y + (end.y - start.y) * factor,
                start.z + (end.z - start.z) * factor
            );
        }
    }
    
    const aiVector3D& pos = channel->mPositionKeys[channel->mNumPositionKeys - 1].mValue;
    return QVector3D(pos.x, pos.y, pos.z);
}

QQuaternion ModelPreview::interpolateRotation(const aiNodeAnim* channel, double time)
{
    if (channel->mNumRotationKeys == 0) {
        return QQuaternion();
    }
    
    // 边界检查
    if (time <= channel->mRotationKeys[0].mTime) {
        const aiQuaternion& rot = channel->mRotationKeys[0].mValue;
        return QQuaternion(rot.w, rot.x, rot.y, rot.z);
    }
    
    if (time >= channel->mRotationKeys[channel->mNumRotationKeys - 1].mTime) {
        const aiQuaternion& rot = channel->mRotationKeys[channel->mNumRotationKeys - 1].mValue;
        return QQuaternion(rot.w, rot.x, rot.y, rot.z);
    }
    
    // 找到当前时间的关键帧
    for (unsigned int i = 0; i < channel->mNumRotationKeys - 1; i++) {
        if (time < channel->mRotationKeys[i + 1].mTime) {
            // 球面线性插值
            double factor = (time - channel->mRotationKeys[i].mTime) / 
                           (channel->mRotationKeys[i + 1].mTime - channel->mRotationKeys[i].mTime);
            
            factor = qBound(0.0, factor, 1.0);
            
            const aiQuaternion& start = channel->mRotationKeys[i].mValue;
            const aiQuaternion& end = channel->mRotationKeys[i + 1].mValue;
            
            QQuaternion startQ(start.w, start.x, start.y, start.z);
            QQuaternion endQ(end.w, end.x, end.y, end.z);
            
            return QQuaternion::slerp(startQ, endQ, factor);
        }
    }
    
    const aiQuaternion& rot = channel->mRotationKeys[channel->mNumRotationKeys - 1].mValue;
    return QQuaternion(rot.w, rot.x, rot.y, rot.z);
}

QVector3D ModelPreview::interpolateScaling(const aiNodeAnim* channel, double time)
{
    if (channel->mNumScalingKeys == 0) {
        return QVector3D(1, 1, 1);
    }
    
    // 边界检查
    if (time <= channel->mScalingKeys[0].mTime) {
        const aiVector3D& scale = channel->mScalingKeys[0].mValue;
        return QVector3D(scale.x, scale.y, scale.z);
    }
    
    if (time >= channel->mScalingKeys[channel->mNumScalingKeys - 1].mTime) {
        const aiVector3D& scale = channel->mScalingKeys[channel->mNumScalingKeys - 1].mValue;
        return QVector3D(scale.x, scale.y, scale.z);
    }
    
    // 找到当前时间的关键帧
    for (unsigned int i = 0; i < channel->mNumScalingKeys - 1; i++) {
        if (time < channel->mScalingKeys[i + 1].mTime) {
            // 线性插值
            double factor = (time - channel->mScalingKeys[i].mTime) / 
                           (channel->mScalingKeys[i + 1].mTime - channel->mScalingKeys[i].mTime);
            
            factor = qBound(0.0, factor, 1.0);
            
            const aiVector3D& start = channel->mScalingKeys[i].mValue;
            const aiVector3D& end = channel->mScalingKeys[i + 1].mValue;
            
            return QVector3D(
                start.x + (end.x - start.x) * factor,
                start.y + (end.y - start.y) * factor,
                start.z + (end.z - start.z) * factor
            );
        }
    }
    
    const aiVector3D& scale = channel->mScalingKeys[channel->mNumScalingKeys - 1].mValue;
    return QVector3D(scale.x, scale.y, scale.z);
}

void ModelPreview::playCurrentAnimation()
{
    if (!m_currentAnimation || !m_scene) {
        qDebug() << "No current animation or scene";
        return;
    }
    
    // 更新动画时间
    m_animationTime += 0.016f; // 约60FPS
    
    // 更新骨骼变换
    updateBoneTransforms(m_animationTime);
    
    qDebug() << "Playing bone animation:" << m_animationList[m_currentAnimationIndex].name 
             << "Time:" << m_animationTime
             << "Bones:" << m_bones.size();
}

void ModelPreview::calculateModelBounds()
{
    if (!m_scene || m_vertices.isEmpty()) {
        return;
    }
    
    // 初始化边界框
    m_modelMin = QVector3D(std::numeric_limits<float>::max(),
                          std::numeric_limits<float>::max(),
                          std::numeric_limits<float>::max());
    m_modelMax = QVector3D(std::numeric_limits<float>::lowest(),
                          std::numeric_limits<float>::lowest(),
                          std::numeric_limits<float>::lowest());
    
    // 遍历所有顶点计算边界框
    // 每个顶点数据包含19个float：位置(3) + 颜色(3) + 纹理坐标(2) + 法线(3) + 骨骼索引(4) + 骨骼权重(4)
    for (int i = 0; i < m_vertices.size(); i += 19) {
        float x = m_vertices[i];
        float y = m_vertices[i + 1];
        float z = m_vertices[i + 2];
        
        m_modelMin.setX(qMin(m_modelMin.x(), x));
        m_modelMin.setY(qMin(m_modelMin.y(), y));
        m_modelMin.setZ(qMin(m_modelMin.z(), z));
        
        m_modelMax.setX(qMax(m_modelMax.x(), x));
        m_modelMax.setY(qMax(m_modelMax.y(), y));
        m_modelMax.setZ(qMax(m_modelMax.z(), z));
    }
    
    // 计算模型中心和大小
    m_modelCenter = (m_modelMin + m_modelMax) * 0.5f;
    QVector3D modelExtent = m_modelMax - m_modelMin;
    m_modelSize = qMax(modelExtent.x(), qMax(modelExtent.y(), modelExtent.z()));
    
    qDebug() << "Model bounds calculated:";
    qDebug() << "  Min:" << m_modelMin;
    qDebug() << "  Max:" << m_modelMax;
    qDebug() << "  Center:" << m_modelCenter;
    qDebug() << "  Size:" << m_modelSize;
}

void ModelPreview::adjustCameraToModel()
{
    if (m_modelSize <= 0) {
        return;
    }
    
    // 计算合适的相机距离
    float distance = m_modelSize * 2.5f; // 确保整个模型可见
    
    // 设置相机位置，从模型正前方观看
    m_cameraPosition = m_modelCenter + QVector3D(0.0f, 0.0f, distance);
    m_cameraTarget = m_modelCenter;
    m_cameraUp = QVector3D(0.0f, 1.0f, 0.0f);
    
    // 重置缩放
    m_zoom = 1.0f;
    
    // 重置旋转
    m_rotation = QQuaternion();
    
    qDebug() << "Camera adjusted to model:";
    qDebug() << "  Position:" << m_cameraPosition;
    qDebug() << "  Target:" << m_cameraTarget;
    qDebug() << "  Distance:" << distance;
}

void ModelPreview::loadTextures(const aiScene *scene, const QString &modelDir)
{
    // 清理现有纹理
    for (GLuint textureID : m_textures) {
        glDeleteTextures(1, &textureID);
    }
    m_textures.clear();
    
    if (!scene || scene->mNumMaterials == 0) {
        qDebug() << "No materials found in scene";
        return;
    }
    
    qDebug() << "Loading textures from" << scene->mNumMaterials << "materials";
    
    // 遍历所有材质查找纹理
    for (unsigned int i = 0; i < scene->mNumMaterials; i++) {
        const aiMaterial *material = scene->mMaterials[i];
        
        // 依次尝试 BASE_COLOR, DIFFUSE, UNKNOWN，加载第一个可用纹理
        const aiTextureType candidateTypes[] = {
            (aiTextureType)aiTextureType_BASE_COLOR,
            aiTextureType_DIFFUSE,
            aiTextureType_UNKNOWN
        };
        bool loadedForMaterial = false;
        for (aiTextureType t : candidateTypes) {
            if (loadedForMaterial) break;
            if (material->GetTextureCount(t) > 0) {
                aiString texturePath;
                if (material->GetTexture(t, 0, &texturePath) == AI_SUCCESS) {
                    QString textureFile = QString::fromUtf8(texturePath.C_Str());
                    qDebug() << "Found texture (type" << (int)t << "):" << textureFile;
                    
                    // 处理嵌入式纹理
                    if (textureFile.startsWith("*")) {
                        // 嵌入式纹理（例如 "*0", "*1" 等）
                        int embeddedIndex = textureFile.mid(1).toInt();
                        if (embeddedIndex < (int)scene->mNumTextures) {
                            const aiTexture *embeddedTexture = scene->mTextures[embeddedIndex];
                            GLuint textureID = loadEmbeddedTexture(embeddedTexture);
                            if (textureID != 0) {
                                m_textures.append(textureID);
                                qDebug() << "Loaded embedded texture" << embeddedIndex << "with ID" << textureID;
                                loadedForMaterial = true;
                            }
                        }
                    } else {
                        // 外部纹理文件
                        QString fullTexturePath = modelDir + "/" + textureFile;
                        GLuint textureID = loadExternalTexture(fullTexturePath);
                        if (textureID != 0) {
                            m_textures.append(textureID);
                            qDebug() << "Loaded external texture:" << fullTexturePath << "with ID" << textureID;
                            loadedForMaterial = true;
                        }
                    }
                }
            }
        }
    }
    
    qDebug() << "Total textures loaded:" << m_textures.size();
}
 
GLuint ModelPreview::loadEmbeddedTexture(const aiTexture *texture)
{
    if (!texture) return 0;
    
    GLuint textureID;
    glGenTextures(1, &textureID);
    glBindTexture(GL_TEXTURE_2D, textureID);
    
    if (texture->mHeight == 0) {
        // 压缩纹理数据
        QByteArray textureData((const char*)texture->pcData, texture->mWidth);
        QImage image;
        if (image.loadFromData(textureData)) {
            QImage glImage = image.convertToFormat(QImage::Format_RGBA8888);
            glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, glImage.width(), glImage.height(), 
                        0, GL_RGBA, GL_UNSIGNED_BYTE, glImage.bits());
        } else {
            qDebug() << "Failed to load embedded compressed texture";
            glDeleteTextures(1, &textureID);
            return 0;
        }
    } else {
        // 未压缩纹理数据
        glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, texture->mWidth, texture->mHeight,
                    0, GL_RGBA, GL_UNSIGNED_BYTE, texture->pcData);
    }
    
    // 设置纹理参数
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
    glGenerateMipmap(GL_TEXTURE_2D);
    
    glBindTexture(GL_TEXTURE_2D, 0);
    return textureID;
}

GLuint ModelPreview::loadExternalTexture(const QString &filePath)
{
    QImage image(filePath);
    if (image.isNull()) {
        qDebug() << "Failed to load texture:" << filePath;
        return 0;
    }
    
    GLuint textureID;
    glGenTextures(1, &textureID);
    glBindTexture(GL_TEXTURE_2D, textureID);
    
    QImage glImage = image.convertToFormat(QImage::Format_RGBA8888);
    glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, glImage.width(), glImage.height(),
                0, GL_RGBA, GL_UNSIGNED_BYTE, glImage.bits());
    
    // 设置纹理参数
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
    glGenerateMipmap(GL_TEXTURE_2D);
    
    glBindTexture(GL_TEXTURE_2D, 0);
    return textureID;
}

// 视图控制方法实现
void ModelPreview::setViewPreset(const QString &preset)
{
    if (preset == "front") {
        setFrontView();
    } else if (preset == "back") {
        setBackView();
    } else if (preset == "left") {
        setLeftView();
    } else if (preset == "right") {
        setRightView();
    } else if (preset == "top") {
        setTopView();
    } else if (preset == "bottom") {
        setBottomView();
    }
}

void ModelPreview::setRotationSensitivity(float sensitivity)
{
    m_rotationSensitivity = sensitivity;
}

void ModelPreview::setAutoAdjustCamera(bool enabled)
{
    m_autoAdjustCamera = enabled;
    qDebug() << "Auto adjust camera:" << (enabled ? "enabled" : "disabled");
}

void ModelPreview::setFrontView()
{
    // 动画播放时使用更大的距离确保模型可见
    float distanceMultiplier = m_isAnimationPlaying ? 3.5f : 2.5f;
    float distance;
    QVector3D target;
    
    if (m_modelSize > 0) {
        distance = m_modelSize * distanceMultiplier;
        target = m_modelCenter;
        qDebug() << "Front view: Using model bounds - ModelSize:" << m_modelSize << "Center:" << m_modelCenter;
    } else {
        // 回退机制：当模型边界框未计算时使用默认值
        distance = 5.0f * distanceMultiplier;
        target = QVector3D(0.0f, 0.0f, 0.0f);
        qDebug() << "Front view: Using fallback distance, model size not available";
    }
    
    m_cameraPosition = target + QVector3D(0.0f, 0.0f, distance);
    m_cameraTarget = target;
    m_cameraUp = QVector3D(0.0f, 1.0f, 0.0f);
    m_rotation = QQuaternion();
    
    qDebug() << "Front view settings:";
    qDebug() << "  Distance:" << distance;
    qDebug() << "  Camera Position:" << m_cameraPosition;
    qDebug() << "  Camera Target:" << m_cameraTarget;
    qDebug() << "  Zoom:" << m_zoom;
    qDebug() << "  Model Loaded:" << m_modelLoaded;
    
    // 标记视图切换，防止动画自动调整干扰
    markViewSwitch();
    
    // 强制重新计算投影矩阵
    resizeGL(width(), height());
    
    update();
    qDebug() << "Set to front view" << (m_isAnimationPlaying ? "(animation active)" : "");
}

void ModelPreview::setBackView()
{
    // 动画播放时使用更大的距离确保模型可见
    float distanceMultiplier = m_isAnimationPlaying ? 3.5f : 2.5f;
    float distance;
    QVector3D target;
    
    if (m_modelSize > 0) {
        distance = m_modelSize * distanceMultiplier;
        target = m_modelCenter;
    } else {
        // 回退机制：当模型边界框未计算时使用默认值
        distance = 5.0f * distanceMultiplier;
        target = QVector3D(0.0f, 0.0f, 0.0f);
        qDebug() << "Back view: Using fallback distance, model size not available";
    }
    
    m_cameraPosition = target + QVector3D(0.0f, 0.0f, -distance);
    m_cameraTarget = target;
    m_cameraUp = QVector3D(0.0f, 1.0f, 0.0f);
    m_rotation = QQuaternion();
    
    qDebug() << "Back view - Distance:" << distance << "Position:" << m_cameraPosition;
    
    // 标记视图切换，防止动画自动调整干扰
    markViewSwitch();
    
    // 强制重新计算投影矩阵
    resizeGL(width(), height());
    
    update();
    qDebug() << "Set to back view" << (m_isAnimationPlaying ? "(animation active)" : "");
}

void ModelPreview::setLeftView()
{
    // 动画播放时使用更大的距离确保模型可见
    float distanceMultiplier = m_isAnimationPlaying ? 3.5f : 2.5f;
    float distance;
    QVector3D target;
    
    if (m_modelSize > 0) {
        distance = m_modelSize * distanceMultiplier;
        target = m_modelCenter;
    } else {
        // 回退机制：当模型边界框未计算时使用默认值
        distance = 5.0f * distanceMultiplier;
        target = QVector3D(0.0f, 0.0f, 0.0f);
        qDebug() << "Left view: Using fallback distance, model size not available";
    }
    
    m_cameraPosition = target + QVector3D(-distance, 0.0f, 0.0f);
    m_cameraTarget = target;
    m_cameraUp = QVector3D(0.0f, 1.0f, 0.0f);
    m_rotation = QQuaternion();
    
    qDebug() << "Left view - Distance:" << distance << "Position:" << m_cameraPosition;
    
    // 标记视图切换，防止动画自动调整干扰
    markViewSwitch();
    
    // 强制重新计算投影矩阵
    resizeGL(width(), height());
    
    update();
    qDebug() << "Set to left view" << (m_isAnimationPlaying ? "(animation active)" : "");
}

void ModelPreview::setRightView()
{
    // 动画播放时使用更大的距离确保模型可见
    float distanceMultiplier = m_isAnimationPlaying ? 3.5f : 2.5f;
    float distance;
    QVector3D target;
    
    if (m_modelSize > 0) {
        distance = m_modelSize * distanceMultiplier;
        target = m_modelCenter;
    } else {
        // 回退机制：当模型边界框未计算时使用默认值
        distance = 5.0f * distanceMultiplier;
        target = QVector3D(0.0f, 0.0f, 0.0f);
        qDebug() << "Right view: Using fallback distance, model size not available";
    }
    
    m_cameraPosition = target + QVector3D(distance, 0.0f, 0.0f);
    m_cameraTarget = target;
    m_cameraUp = QVector3D(0.0f, 1.0f, 0.0f);
    m_rotation = QQuaternion();
    
    qDebug() << "Right view - Distance:" << distance << "Position:" << m_cameraPosition;
    
    // 标记视图切换，防止动画自动调整干扰
    markViewSwitch();
    
    // 强制重新计算投影矩阵
    resizeGL(width(), height());
    
    update();
    qDebug() << "Set to right view" << (m_isAnimationPlaying ? "(animation active)" : "");
}

void ModelPreview::setTopView()
{
    // 动画播放时使用更大的距离确保模型可见
    float distanceMultiplier = m_isAnimationPlaying ? 3.5f : 2.5f;
    float distance;
    QVector3D target;
    
    if (m_modelSize > 0) {
        distance = m_modelSize * distanceMultiplier;
        target = m_modelCenter;
    } else {
        // 回退机制：当模型边界框未计算时使用默认值
        distance = 5.0f * distanceMultiplier;
        target = QVector3D(0.0f, 0.0f, 0.0f);
        qDebug() << "Top view: Using fallback distance, model size not available";
    }
    
    m_cameraPosition = target + QVector3D(0.0f, distance, 0.0f);
    m_cameraTarget = target;
    m_cameraUp = QVector3D(0.0f, 0.0f, -1.0f);
    m_rotation = QQuaternion();
    
    qDebug() << "Top view - Distance:" << distance << "Position:" << m_cameraPosition;
    
    // 标记视图切换，防止动画自动调整干扰
    markViewSwitch();
    
    // 强制重新计算投影矩阵
    resizeGL(width(), height());
    
    update();
    qDebug() << "Set to top view" << (m_isAnimationPlaying ? "(animation active)" : "");
}

void ModelPreview::setBottomView()
{
    // 动画播放时使用更大的距离确保模型可见
    float distanceMultiplier = m_isAnimationPlaying ? 3.5f : 2.5f;
    float distance;
    QVector3D target;
    
    if (m_modelSize > 0) {
        distance = m_modelSize * distanceMultiplier;
        target = m_modelCenter;
    } else {
        // 回退机制：当模型边界框未计算时使用默认值
        distance = 5.0f * distanceMultiplier;
        target = QVector3D(0.0f, 0.0f, 0.0f);
        qDebug() << "Bottom view: Using fallback distance, model size not available";
    }
    
    m_cameraPosition = target + QVector3D(0.0f, -distance, 0.0f);
    m_cameraTarget = target;
    m_cameraUp = QVector3D(0.0f, 0.0f, 1.0f);
    m_rotation = QQuaternion();
    
    qDebug() << "Bottom view - Distance:" << distance << "Position:" << m_cameraPosition;
    
    // 标记视图切换，防止动画自动调整干扰
    markViewSwitch();
    
    // 强制重新计算投影矩阵
    resizeGL(width(), height());
    
    update();
    qDebug() << "Set to bottom view" << (m_isAnimationPlaying ? "(animation active)" : "");
}

void ModelPreview::adjustCameraForAnimation()
{
    if (!m_autoAdjustCamera || !m_isAnimationPlaying || m_modelSize <= 0) {
        return;
    }
    
    // 检查是否在视图切换后的短时间内，如果是则跳过调整
    if (m_viewSwitchInProgress && m_lastViewSwitch.elapsed() < 1000) { // 1秒保护期
        return;
    }
    m_viewSwitchInProgress = false;
    
    // 在动画播放时，确保相机距离足够远以包含整个动画范围
    // 动画可能会使模型移动超出原始边界框
    float currentDistance = (m_cameraPosition - m_cameraTarget).length();
    float recommendedDistance = m_modelSize * 3.5f;
    
    // 只有当距离明显不足时才调整，避免与手动视图切换冲突
    if (currentDistance < recommendedDistance * 0.8f) { // 增加缓冲区
        QVector3D direction = (m_cameraPosition - m_cameraTarget).normalized();
        QVector3D newPosition = m_cameraTarget + direction * recommendedDistance;
        
        // 使用更缓慢的过渡，避免突兀的相机跳跃
        float lerpFactor = 0.01f; // 减少调整强度
        m_cameraPosition = m_cameraPosition * (1.0f - lerpFactor) + newPosition * lerpFactor;
        
        qDebug() << "Auto-adjusting camera during animation - Distance:" << currentDistance << "-> Recommended:" << recommendedDistance;
    }
}

// 新增：标记视图切换发生
void ModelPreview::markViewSwitch()
{
    m_lastViewSwitch = QTime::currentTime();
    m_viewSwitchInProgress = true;
    
    qDebug() << "View switch marked - animation auto-adjust disabled for 1 second";
}

void ModelPreview::debugRenderState()
{
    qDebug() << "=== ModelPreview Debug State ===";
    qDebug() << "Model Loaded:" << m_modelLoaded;
    qDebug() << "Scene Valid:" << (m_scene != nullptr);
    qDebug() << "Model Size:" << m_modelSize;
    qDebug() << "Model Center:" << m_modelCenter;
    qDebug() << "Camera Position:" << m_cameraPosition;
    qDebug() << "Camera Target:" << m_cameraTarget;
    qDebug() << "Camera Up:" << m_cameraUp;
    qDebug() << "Zoom:" << m_zoom;
    qDebug() << "Rotation:" << m_rotation;
    qDebug() << "Vertices Count:" << m_vertices.size();
    qDebug() << "Indices Count:" << m_indices.size();
    qDebug() << "Animation Playing:" << m_isAnimationPlaying;
    qDebug() << "Widget Size:" << width() << "x" << height();
    qDebug() << "================================";
}